package servlet.admin;

import entity.Manager;
import entity.Util;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import service.admin.ManagerListService;
import service.admin.impl.ManagerListServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * ManagerList
 *
 * @author ChenYanMei
 * @version 2023/9/4
 */
@WebServlet("/admin/managerList")
public class ManagerListServlet extends HttpServlet {
    ManagerListService service = new ManagerListServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json; charset=utf8");
        req.setCharacterEncoding("utf-8");

        // 返回数据
        int code = 1;
        String msg = "error";
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        PrintWriter out = resp.getWriter();
            List<Manager> list = service.getList();
            for (Manager manager: list) {
                jsonObject.put("id", manager.getId());
                jsonObject.put("name", manager.getName());
                jsonObject.put("account", manager.getAccount());
                jsonObject.put("password",manager.getPassword());
                jsonObject.put("email", manager.getEmail());
                jsonArray.add(jsonObject);
            }

            if (!jsonArray.isEmpty()) {
                code = 0;
                msg = "查询成功";
            } else {
                msg = "数据为空";
            }
            out.print(Util.jsonResponse(code, msg, jsonArray.toString()));
    }
}
